#!/bin/bash

# 配置路径（Windows环境需修改为实际路径）
DEVECO_DIR="D:\Program Files\Huawei\DevEco Studio51110"
DEVECO_PATH="${DEVECO_DIR}/bin/devecostudio64.exe"
TARGET_DIR="sharedlibrary"

# 环境检查
check_dependencies() {
    command -v git >/dev/null 2>&1 || { echo >&2 "Git未安装"; exit 1; }
    node -v >/dev/null 2>&1 || { echo >&2 "Node.js未安装"; exit 1; }
    ohpm -v >/dev/null 2>&1 || { echo >&2 "OHPM未安装"; exit 1; }
}

install_node() {
    if npm list json5 --depth=0 --silent > /dev/null 2>$1; then
        echo "➜ json5 已安装，跳过安装"
    else
        echo "➜ 正在安装 json5..."
        npm install json5
    fi
}

# 核心流程
clone_and_build() {
    local owner=$1
    local name=$2
    local sub_dir=$3

    # 禁用克隆保护机制
    GIT_CLONE_PROTECTION_ACTIVE=false

    if [ -d "$name" ]; then
        cp modifyConfig.js $name
        cd "$name" || exit 1
    else
        # 特殊处理 openharmony-tpc/openharmony_tpc_samples
        if [ "$owner" = "openharmony-tpc" ] && [ "$name" = "openharmony_tpc_samples" ]; then
            if [ ! -d "$name" ]; then  # Only clone if directory doesn't exist
                # Check if sub_dir requires --recurse-submodules
                case "$sub_dir" in
                    socketio|socketio_2.x|socketio_tls|vap|ohos_minizip)
                        git clone https://gitcode.com/$owner/$name.git --recurse-submodules || exit 1
                        ;;
                    *)
                        git clone https://gitcode.com/$owner/$name.git || exit 1
                        ;;
                esac
            fi
            # Directory already exists, pull the latest code
            echo "Directory '$name' already exists. Pulling latest code..."
            cd "$name" || exit 1
            git pull || exit 1
            cd ..  # Return to the parent directory
        else
            # Check if repository requires --recursive
            case "$name" in
                ohos_grpc_node|ohos_mqtt|ohos_coap|mp4parser|ohos_videocompressor|jtar)
                    git clone https://gitcode.com/$owner/$name.git --recursive || exit 1
                    ;;
                *)
                    git clone https://gitcode.com/$owner/$name.git || exit 1
                    ;;
            esac
        fi
        cp modifyConfig.js $name
        cd "$name" || exit 1
    fi

    if [ -n "$sub_dir" ]; then
        if [ -d "$sub_dir" ]; then
        cp modifyConfig.js $sub_dir
            cd "$sub_dir" || exit 1
        else
            echo "错误：子目录 '$sub_dir' 不存在！"
            exit 1
        fi
    fi

    install_node

    # 启动DevEco Studio（Windows环境）
    # start "" "$DEVECO_PATH" .
    # sleep 10

    # 使用新函数替代原来的自动化迁移操作
    node modifyConfig.js

    # 命令行构建
    ohpm install --all --registry https://ohpm.openharmony.cn/ohpm --strict_ssl true || exit 1
    "${DEVECO_DIR}\tools\node\node.exe" "${DEVECO_DIR}\tools\hvigor\bin\hvigorw.js" --sync -p product=default --analyze=normal --parallel --incremental --daemon

    # 强制校验必要文件
    required_files=("README.md" "LICENSE" "CHANGELOG.md")
    for file in "${required_files[@]}"; do
        if [ ! -f "$file" ]; then
            echo "错误：必要文件$file缺失" >&2
            exit 1
        fi
        cp -v "$file" library/ || exit 1
    done

    # 可选文件处理
    if [ -f "README_zh.md" ]; then
        cp -v README_zh.md library/ || exit 1
    fi

    if [ -f "README.OpenSource" ]; then
        cp -v README.OpenSource library/ || exit 1
    fi

    if [ -f "NOTICE" ]; then
        cp -v NOTICE library/ || exit 1
    fi

    if [ -f "TEST.md" ]; then
        cp -v TEST.md library/ || exit 1
    fi

    # 生成HAR包
    "${DEVECO_DIR}\tools\node\node.exe" "${DEVECO_DIR}\tools\hvigor\bin\hvigorw.js"  --mode module -p product=default -p module=library@default assembleHar --analyze=normal --parallel --incremental --daemon

    # OHPM发布
    # ohpm config set registry https://ohpm.openharmony.cn/ohpm
    cd library/build/default/outputs/default/ || exit 1
    ohpm publish library.har 

    # 清理项目目录（除非是 openharmony_tpc_samples）
    if [ "$name" != "openharmony_tpc_samples" ]; then
        echo "Cleaning up project directory: $name"
        cd ../../../../../../.. || exit 1  # 返回到项目根目录
        rm -rf "$name"
    else
        echo "Skipping cleanup for project: $name"
    fi
}

matches_library_name() {
    read -p "请输入关键词（比如circle）：" keyword

    json_file="Library.json"

    results=$(sed -n '/{/,/}/p' "$json_file" | awk -v keyword="$keyword" '
    {
        # 精准提取键值对
        if (match($0, /"owner"[[:space:]]*:[[:space:]]*"([^"]+)"/, m)) {
            owner = m[1]
        }
        if (match($0, /"name"[[:space:]]*:[[:space:]]*"([^"]+)"/, m)) {
            name = m[1]
        }
        if (match($0, /"sub_dir"[[:space:]]*:[[:space:]]*"([^"]+)"/, m)) {
            sub_dir = m[1]
        }
        # 遇到右括号时处理
        if ($0 ~ /}/) {
            if (owner ~ keyword || name ~ keyword || sub_dir ~ keyword ) {
                print owner, name, sub_dir
            }
            owner = name = sub_dir = ""  # 重置变量
        }
    }')

    if [ -z "$results" ]; then
        echo "未找到匹配的仓库信息。"
        exit 1
    fi

    echo "匹配的仓库信息："
    declare -i index=1
    declare -A matches
    while read -r owner name sub_dir; do
        echo "$index. owner: $owner, name: $name, sub_dir: $sub_dir"
        matches[$index]="$owner $name $sub_dir"
        index+=1
    done <<< "$results"

    read -p "请选择要执行的操作（输入编号）：" choice
    if [[ -z "${matches[$choice]}" ]]; then
        echo "无效选择！"
        exit 1
    fi

    IFS=' ' read -r owner name sub_dir <<< "${matches[$choice]}"
    clone_and_build "$owner" "$name" "$sub_dir"
}   


# 执行主流程
matches_library_name
check_dependencies